package cn.tedu.micro.demo.order.service.impl;

import cn.tedu.micro.demo.common.protocol.JsonResult;
import cn.tedu.micro.demo.common.vo.GunInfoVO;
import cn.tedu.micro.demo.order.clients.DeviceClient;
import cn.tedu.micro.demo.order.dao.repository.OrderRepository;
import cn.tedu.micro.demo.order.pojo.po.OrderInfoPO;
import cn.tedu.micro.demo.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    /**
     * 创建订单
     *
     * @param gunId  枪ID
     * @param userId 用户ID
     * @return 订单ID
     */
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DeviceClient deviceClient;
    @Override
    public String createOrder(Integer gunId, Integer userId) {
        log.info("开始处理创建订单业务，参数:userId={},gunId={}",userId,gunId);
        // 利用枪id查询枪状态
       Integer status = checkGunStatus(gunId);
       if (status != 1) {
           log.error("枪状态异常,无法下单");
           throw new RuntimeException("枪状态异常,无法下单");
       }else{
           log.info("开始处理创建订单业务，参数:userId={},gunId={}",userId,gunId);
           //2.生成订单编号
           String billId = UUID.randomUUID().toString().replace("-", "");
           //3.封装po
           OrderInfoPO orderInfoPO = new OrderInfoPO();
           orderInfoPO.setBillId(billId);
           orderInfoPO.setGunId(gunId);
           orderInfoPO.setUserId(userId);
           //4.保存到数据库
           orderRepository.saveOrder(orderInfoPO);
           log.info("订单创建成功，订单编号:{}",billId);
           return billId;
       }

    }

    private Integer checkGunStatus(Integer gunId) {
        //1.调用feingClient接口
        JsonResult<GunInfoVO> result = deviceClient.checkGunStatus(gunId);
        //2.读取判断调用结果 如果code!=0说明调用失败 抛出异常逻辑流程结束
        if(result.getCode() != 0){
            log.error("调用设备服务失败,异常信息:{}",result.getMessage());
            throw new RuntimeException("调用设备服务失败");
        }else{
            GunInfoVO vo = result.getData();

            return vo.getStatus();
        }

    }
}
